#include "downloaddelegate.h"
#include "downloadmodel.h"

#include <QPainter>
#include <QStyleOptionViewItem>
#include <QModelIndex>
#include <QDebug>
#include <QApplication>

DownloadDelegate::DownloadDelegate(DownloadModel* dataModel, QObject *parent) :
    QStyledItemDelegate(parent)
{
    model = dataModel;
}

void DownloadDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (index.column() != 4) {
        QStyledItemDelegate::paint(painter, option, index);
        return;
    }

    QStyleOptionProgressBar progressBarOption;
    progressBarOption.state = QStyle::State_Enabled;
    progressBarOption.direction = QApplication::layoutDirection();
    progressBarOption.rect = option.rect;
    progressBarOption.fontMetrics = QApplication::fontMetrics();
    progressBarOption.minimum = 0;
    progressBarOption.maximum = 100;
    progressBarOption.textAlignment = Qt::AlignCenter;
    progressBarOption.textVisible = true;

    // Set the progress and text values of the style option.
    int bytesReceived = model->data(index).toInt();
    QModelIndex totalIndex = model->index(index.row(), index.column() - 1);
    int totalBytes = model->data(totalIndex).toInt();
    int progress;
    if (totalBytes != 0) {
        progress = (int)(((double)bytesReceived / totalBytes) * 100);
    } else {
        progress = 0;
    }
    progressBarOption.progress = progress < 0 ? 0 : progress;
    progressBarOption.text = QString().sprintf("%d%%", progressBarOption.progress);

    // Draw the progress bar onto the view.
    QApplication::style()->drawControl(QStyle::CE_ProgressBar, &progressBarOption, painter);

}






